const utils = require('j7/utils');
const BaseService = require('./baseservice');
const metaFactory = require('../metadata/factory');
const bcClass = require('../blockchain');

const netIdHash = {};

function getBc(netId) {
  return utils.hasKey(netIdHash, netId) ? netIdHash[netId] : null;
}

class BlockChain extends BaseService {

  #bc = null;

  static async staticInit() {
    metaFactory.getNetList().forEach(async (netId) => {
      const bc = new bcClass(netId);
      netIdHash[netId] = bc;
      await bc.init();
    });
  }

  async init(netId) {
    this.#bc = getBc(netId);
    return this.#bc != null;
  }

  getNftAddress(tokenType) {
    return this.#bc.getNftAddress(tokenType);
  }

  getUserAddress() {
    return this.#bc.getUserAddress();
  }

  isValidAddress(address) {
    return this.#bc.isValidAddress(address);
  }

  getContractAddressByName(name) {
    const c = this.#bc.getContractByName(name);
    return c ? c['address'] : '';
  }

  getContractByName(name) {
    const c = this.#bc.getContractByName(name);
    return c;
  }

  getCurrencyAddressByName(currencyName) {
    return this.#bc.getCurrencyAddressByName(currencyName);
  }

  getInstanceByName(name) {
    return this.#bc[`${name}Instance`];
  }

  async soliditySha3Sign(...args) {
    const signStr = await this.#bc.web3.utils.soliditySha3(...args);
    let signature = await this.#bc.web3.eth.sign(signStr, this.getUserAddress());
    signature = signature.replace(/00$/, "1b").replace(/01$/, "1c");
    return signature;
  }

}

module.exports = BlockChain;
